3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
26 use Wikimedia\WaitConditionLoop
;
33 class DatabasePostgres
extends Database
{
38 protected $lastResultHandle = null;
40 /** @var float|string */
41 private $numericVersion = null;
42 /** @var string Connect string to open a PostgreSQL connection */
43 private $connectString;
48 /** @var string[] Map of (reserved table name => alternate table name) */
49 private $keywordTableMap = [];
52 * @see Database::__construct()
53 * @param array $params Additional parameters include:
54 * - keywordTableMap : Map of reserved table names to alternative table names to use
56 public function __construct( array $params ) {
57 $this->port
= $params['port'] ??
false;
58 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
60 parent
::__construct( $params );
63 public function getType() {
67 public function implicitGroupby() {
71 public function implicitOrderby() {
75 public function hasConstraint( $name ) {
76 foreach ( $this->getCoreSchemas() as $schema ) {
77 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = " .
79 $this->addQuotes( $name ) . " AND n.nspname = " .
80 $this->addQuotes( $schema );
81 $res = $this->doQuery( $sql );
82 if ( $res && $this->numRows( $res ) ) {
89 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
90 // Test for Postgres support, to avoid suppressed fatal error
91 if ( !function_exists( 'pg_connect' ) ) {
92 throw new DBConnectionError(
94 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96 "webserver and database)\n"
102 $this->server
= $server;
104 $this->password
= $password;
107 // pg_connect() user $user as the default database. Since a database is *required*,
108 // at least pick a "don't care" database that is more likely to exist. This case
109 // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
110 'dbname' => strlen( $dbName ) ?
$dbName : 'postgres',
112 'password' => $password
114 if ( $server != false && $server != '' ) {
115 $connectVars['host'] = $server;
117 if ( (int)$this->port
> 0 ) {
118 $connectVars['port'] = (int)$this->port
;
120 if ( $this->flags
& self
::DBO_SSL
) {
121 $connectVars['sslmode'] = 'require';
124 $this->connectString
= $this->makeConnectionString( $connectVars );
126 $this->installErrorHandler();
128 // Use new connections to let LoadBalancer/LBFactory handle reuse
129 $this->conn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
130 } catch ( Exception
$ex ) {
131 $this->restoreErrorHandler();
134 $phpError = $this->restoreErrorHandler();
136 if ( !$this->conn
) {
137 $this->queryLogger
->debug(
138 "DB connection error\n" .
139 "Server: $server, Database: $dbName, User: $user, Password: " .
140 substr( $password, 0, 3 ) . "...\n"
142 $this->queryLogger
->debug( $this->lastError() . "\n" );
143 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
147 // If called from the command-line (e.g. importDump), only show errors.
148 // No transaction should be open at this point, so the problem of the SET
149 // effects being rolled back should not be an issue.
150 // See https://www.postgresql.org/docs/8.3/sql-set.html
152 if ( $this->cliMode
) {
153 $variables['client_min_messages'] = 'ERROR';
156 'client_encoding' => 'UTF8',
157 'datestyle' => 'ISO, YMD',
159 'standard_conforming_strings' => 'on',
160 'bytea_output' => 'escape'
162 foreach ( $variables as $var => $val ) {
164 'SET ' . $this->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val ),
166 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
170 $this->determineCoreSchema( $schema );
171 $this->currentDomain
= new DatabaseDomain( $dbName, $schema, $tablePrefix );
172 } catch ( Exception
$e ) {
173 // Connection was not fully initialized and is not safe for use
178 protected function relationSchemaQualifier() {
179 if ( $this->coreSchema
=== $this->currentDomain
->getSchema() ) {
180 // The schema to be used is now in the search path; no need for explicit qualification
184 return parent
::relationSchemaQualifier();
187 public function databasesAreIndependent() {
191 public function doSelectDomain( DatabaseDomain
$domain ) {
192 if ( $this->getDBname() !== $domain->getDatabase() ) {
193 // Postgres doesn't support selectDB in the same way MySQL does.
194 // So if the DB name doesn't match the open connection, open a new one
199 $domain->getDatabase(),
200 $domain->getSchema(),
201 $domain->getTablePrefix()
204 $this->currentDomain
= $domain;
211 * @param string[] $vars
214 private function makeConnectionString( $vars ) {
216 foreach ( $vars as $name => $value ) {
217 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
223 protected function closeConnection() {
224 return $this->conn ?
pg_close( $this->conn
) : true;
227 protected function isTransactableQuery( $sql ) {
228 return parent
::isTransactableQuery( $sql ) &&
229 !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
234 * @return bool|mixed|resource
236 public function doQuery( $sql ) {
237 $conn = $this->getBindingHandle();
239 $sql = mb_convert_encoding( $sql, 'UTF-8' );
240 // Clear previously left over PQresult
241 while ( $res = pg_get_result( $conn ) ) {
242 pg_free_result( $res );
244 if ( pg_send_query( $conn, $sql ) === false ) {
245 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
247 $this->lastResultHandle
= pg_get_result( $conn );
248 if ( pg_result_error( $this->lastResultHandle
) ) {
252 return $this->lastResultHandle
;
255 protected function dumpError() {
259 PGSQL_DIAG_MESSAGE_PRIMARY
,
260 PGSQL_DIAG_MESSAGE_DETAIL
,
261 PGSQL_DIAG_MESSAGE_HINT
,
262 PGSQL_DIAG_STATEMENT_POSITION
,
263 PGSQL_DIAG_INTERNAL_POSITION
,
264 PGSQL_DIAG_INTERNAL_QUERY
,
266 PGSQL_DIAG_SOURCE_FILE
,
267 PGSQL_DIAG_SOURCE_LINE
,
268 PGSQL_DIAG_SOURCE_FUNCTION
270 foreach ( $diags as $d ) {
271 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
272 $d, pg_result_error_field( $this->lastResultHandle
, $d ) ) );
276 public function freeResult( $res ) {
277 Wikimedia\
suppressWarnings();
278 $ok = pg_free_result( ResultWrapper
::unwrap( $res ) );
279 Wikimedia\restoreWarnings
();
281 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
285 public function fetchObject( $res ) {
286 Wikimedia\
suppressWarnings();
287 $row = pg_fetch_object( ResultWrapper
::unwrap( $res ) );
288 Wikimedia\restoreWarnings
();
289 # @todo FIXME: HACK HACK HACK HACK debug
291 # @todo hashar: not sure if the following test really trigger if the object
293 $conn = $this->getBindingHandle();
294 if ( pg_last_error( $conn ) ) {
295 throw new DBUnexpectedError(
297 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
304 public function fetchRow( $res ) {
305 Wikimedia\
suppressWarnings();
306 $row = pg_fetch_array( ResultWrapper
::unwrap( $res ) );
307 Wikimedia\restoreWarnings
();
309 $conn = $this->getBindingHandle();
310 if ( pg_last_error( $conn ) ) {
311 throw new DBUnexpectedError(
313 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
320 public function numRows( $res ) {
321 if ( $res === false ) {
325 Wikimedia\
suppressWarnings();
326 $n = pg_num_rows( ResultWrapper
::unwrap( $res ) );
327 Wikimedia\restoreWarnings
();
329 $conn = $this->getBindingHandle();
330 if ( pg_last_error( $conn ) ) {
331 throw new DBUnexpectedError(
333 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
340 public function numFields( $res ) {
341 return pg_num_fields( ResultWrapper
::unwrap( $res ) );
344 public function fieldName( $res, $n ) {
345 return pg_field_name( ResultWrapper
::unwrap( $res ), $n );
348 public function insertId() {
349 $res = $this->query( "SELECT lastval()" );
350 $row = $this->fetchRow( $res );
351 return is_null( $row[0] ) ?
null : (int)$row[0];
354 public function dataSeek( $res, $row ) {
355 return pg_result_seek( ResultWrapper
::unwrap( $res ), $row );
358 public function lastError() {
360 if ( $this->lastResultHandle
) {
361 return pg_result_error( $this->lastResultHandle
);
363 return pg_last_error();
367 return $this->getLastPHPError() ?
: 'No database connection';
370 public function lastErrno() {
371 if ( $this->lastResultHandle
) {
372 return pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
378 protected function fetchAffectedRowCount() {
379 if ( !$this->lastResultHandle
) {
383 return pg_affected_rows( $this->lastResultHandle
);
387 * Estimate rows in dataset
388 * Returns estimated count, based on EXPLAIN output
389 * This is not necessarily an accurate estimate, so use sparingly
390 * Returns -1 if count cannot be found
391 * Takes same arguments as Database::select()
393 * @param string $table
395 * @param string $conds
396 * @param string $fname
397 * @param array $options
398 * @param array $join_conds
401 public function estimateRowCount( $table, $var = '*', $conds = '',
402 $fname = __METHOD__
, $options = [], $join_conds = []
404 $conds = $this->normalizeConditions( $conds, $fname );
405 $column = $this->extractSingleFieldFromList( $var );
406 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
407 $conds[] = "$column IS NOT NULL";
410 $options['EXPLAIN'] = true;
411 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
414 $row = $this->fetchRow( $res );
416 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
417 $rows = (int)$count[1];
424 public function indexInfo( $table, $index, $fname = __METHOD__
) {
425 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
426 $res = $this->query( $sql, $fname );
430 foreach ( $res as $row ) {
431 if ( $row->indexname
== $this->indexName( $index ) ) {
439 public function indexAttributes( $index, $schema = false ) {
440 if ( $schema === false ) {
441 $schemas = $this->getCoreSchemas();
443 $schemas = [ $schema ];
446 $eindex = $this->addQuotes( $index );
448 foreach ( $schemas as $schema ) {
449 $eschema = $this->addQuotes( $schema );
451 * A subquery would be not needed if we didn't care about the order
452 * of attributes, but we do
454 $sql = <<<__INDEXATTR__
458 i.indoption[s.g] as option,
461 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
465 ON cis.oid=isub.indexrelid
467 ON cis.relnamespace = ns.oid
468 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
474 ON ci.oid=i.indexrelid
476 ON ct.oid = i.indrelid
478 ON ci.relnamespace = n.oid
480 ci.relname=$eindex AND n.nspname=$eschema
481 AND attrelid = ct.oid
482 AND i.indkey[s.g] = attnum
483 AND i.indclass[s.g] = opcls.oid
484 AND pg_am.oid = opcls.opcmethod
486 $res = $this->query( $sql, __METHOD__ );
489 foreach ( $res as $row ) {
502 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
503 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
504 " AND indexdef LIKE 'CREATE UNIQUE%(" .
505 $this->strencode( $this->indexName( $index ) ) .
507 $res = $this->query( $sql, $fname );
512 return $res->numRows() > 0;
515 public function selectSQLText(
516 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
518 if ( is_string( $options ) ) {
519 $options = [ $options ];
522 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
523 // to the parent function to get the actual SQL text.
524 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
525 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
526 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
528 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
529 if ( is_array( $options ) ) {
530 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
531 if ( $forUpdateKey !== false && $join_conds ) {
532 unset( $options[$forUpdateKey] );
533 $options['FOR UPDATE'] = [];
538 $alias = key( $toCheck );
539 $name = $toCheck[$alias];
540 unset( $toCheck[$alias] );
542 $hasAlias = !is_numeric( $alias );
543 if ( !$hasAlias && is_string( $name ) ) {
547 if ( !isset( $join_conds[$alias] ) ||
548 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
550 if ( is_array( $name ) ) {
551 // It's a parenthesized group, process all the tables inside the group.
552 $toCheck = array_merge( $toCheck, $name );
554 // Quote alias names so $this->tableName() won't mangle them
555 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
561 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
562 unset( $options['ORDER BY'] );
566 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
570 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
571 if ( !count( $args ) ) {
575 $table = $this->tableName( $table );
576 if ( !isset( $this->numericVersion ) ) {
577 $this->getServerVersion();
580 if ( !is_array( $options ) ) {
581 $options = [ $options ];
584 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
586 $keys = array_keys( $args[0] );
589 $keys = array_keys( $args );
592 $ignore = in_array( 'IGNORE', $options );
594 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
596 if ( $this->numericVersion >= 9.5 || !$ignore ) {
597 // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
599 foreach ( $rows as $row ) {
605 $sql .= '(' . $this->makeList( $row ) . ')';
608 $sql .= ' ON CONFLICT DO NOTHING';
610 $this->query( $sql, $fname );
612 // Emulate IGNORE by doing each row individually, with savepoints
613 // to roll back as necessary.
614 $numrowsinserted = 0;
616 $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
618 foreach ( $rows as $row ) {
620 $tempsql .= '(' . $this->makeList( $row ) . ')';
622 $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
624 $this->query( $tempsql, $fname );
625 $this->endAtomic( "$fname (inner)" );
627 } catch ( DBQueryError $e ) {
628 $this->cancelAtomic( "$fname (inner)" );
629 // Our IGNORE is supposed to ignore duplicate key errors, but not others.
630 // (even though MySQL's version apparently ignores all errors)
631 if ( $e->errno !== '23505' ) {
636 } catch ( Exception $e ) {
637 $this->cancelAtomic( "$fname (outer)", $tok );
640 $this->endAtomic( "$fname (outer)" );
642 // Set the affected row count for the whole operation
643 $this->affectedRowCount = $numrowsinserted;
649 protected function makeUpdateOptionsArray( $options ) {
650 if ( !is_array( $options ) ) {
651 $options = [ $options ];
654 // PostgreSQL doesn't support anything like "ignore" for
656 $options = array_diff( $options, [ 'IGNORE' ] );
658 return parent::makeUpdateOptionsArray( $options );
662 * INSERT SELECT wrapper
663 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
664 * Source items may be literals rather then field names, but strings should
665 * be quoted with Database::addQuotes()
666 * $conds may be "*" to copy the whole table
667 * srcTable may be an array of tables.
668 * @todo FIXME: Implement this a little better (separate select/insert)?
670 * @param string $destTable
671 * @param array|string $srcTable
672 * @param array $varMap
673 * @param array $conds
674 * @param string $fname
675 * @param array $insertOptions
676 * @param array $selectOptions
677 * @param array $selectJoinConds
679 protected function nativeInsertSelect(
680 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
681 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
683 if ( !is_array( $insertOptions ) ) {
684 $insertOptions = [ $insertOptions ];
687 if ( in_array( 'IGNORE', $insertOptions ) ) {
688 if ( $this->getServerVersion() >= 9.5 ) {
689 // Use ON CONFLICT DO NOTHING if we have it for IGNORE
690 $destTable = $this->tableName( $destTable );
692 $selectSql = $this->selectSQLText(
694 array_values( $varMap ),
701 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
702 $selectSql . ' ON CONFLICT DO NOTHING';
704 $this->query( $sql, $fname );
706 // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
707 $this->nonNativeInsertSelect(
708 $destTable, $srcTable, $varMap, $conds, $fname,
709 $insertOptions, $selectOptions, $selectJoinConds
713 parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
714 $insertOptions, $selectOptions, $selectJoinConds );
718 public function tableName( $name, $format = 'quoted' ) {
719 // Replace reserved words with better ones
720 $name = $this->remappedTableName( $name );
722 return parent::tableName( $name, $format );
726 * @param string $name
727 * @return string Value of $name or remapped name if $name is a reserved keyword
729 public function remappedTableName( $name ) {
730 return $this->keywordTableMap[$name] ?? $name;
734 * @param string $name
735 * @param string $format
736 * @return string Qualified and encoded (if requested) table name
738 public function realTableName( $name, $format = 'quoted' ) {
739 return parent::tableName( $name, $format );
742 public function nextSequenceValue( $seqName ) {
743 return new NextSequenceValue;
747 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
749 * @param string $seqName
752 public function currentSequenceValue( $seqName ) {
753 $safeseq = str_replace( "'", "''", $seqName );
754 $res = $this->query( "SELECT currval('$safeseq')" );
755 $row = $this->fetchRow( $res );
761 public function textFieldSize( $table, $field ) {
762 $table = $this->tableName( $table );
763 $sql = "SELECT t.typname as ftype,a.atttypmod as size
764 FROM pg_class c, pg_attribute a, pg_type t
765 WHERE relname='$table' AND a.attrelid=c.oid AND
766 a.atttypid=t.oid and a.attname='$field'";
767 $res = $this->query( $sql );
768 $row = $this->fetchObject( $res );
769 if ( $row->ftype == 'varchar' ) {
770 $size = $row->size - 4;
778 public function limitResult( $sql, $limit, $offset = false ) {
779 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
782 public function wasDeadlock() {
783 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
784 return $this->lastErrno() === '40P01';
787 public function wasLockTimeout() {
788 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
789 return $this->lastErrno() === '55P03';
792 public function wasConnectionError( $errno ) {
793 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
794 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
796 return in_array( $errno, $codes, true );
799 protected function wasKnownStatementRollbackError() {
800 return false; // transaction has to be rolled-back from error state
803 public function duplicateTableStructure(
804 $oldName, $newName, $temporary = false, $fname = __METHOD__
806 $newNameE = $this->addIdentifierQuotes( $newName );
807 $oldNameE = $this->addIdentifierQuotes( $oldName );
809 $temporary = $temporary ? 'TEMPORARY' : '';
812 "CREATE $temporary TABLE $newNameE " .
813 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
815 $this::QUERY_PSEUDO_PERMANENT
821 $res = $this->query( 'SELECT attname FROM pg_class c'
822 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
823 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
824 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
825 . ' WHERE relkind = \'r\''
826 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
827 . ' AND relname = ' . $this->addQuotes( $oldName )
828 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
831 $row = $this->fetchObject( $res );
833 $field = $row->attname;
834 $newSeq = "{$newName}_{$field}_seq";
835 $fieldE = $this->addIdentifierQuotes( $field );
836 $newSeqE = $this->addIdentifierQuotes( $newSeq );
837 $newSeqQ = $this->addQuotes( $newSeq );
839 "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
843 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
851 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
852 $table = $this->tableName( $table, 'raw' );
853 foreach ( $this->getCoreSchemas() as $schema ) {
855 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
856 . ' WHERE relkind = \'r\''
857 . ' AND nspname = ' . $this->addQuotes( $schema )
858 . ' AND relname = ' . $this->addQuotes( $table ),
861 if ( !$res || !$this->numRows( $res ) ) {
865 $oid = $this->fetchObject( $res )->oid;
866 $res = $this->query( 'SELECT pg_get_expr(adbin, adrelid) AS adsrc FROM pg_attribute a'
867 . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
868 . " WHERE a.attrelid = $oid"
869 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
872 $row = $this->fetchObject( $res );
875 'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
887 * @suppress SecurityCheck-SQLInjection array_map not recognized T204911
889 public function listTables( $prefix = null, $fname = __METHOD__ ) {
890 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
891 $result = $this->query(
892 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
895 foreach ( $result as $table ) {
896 $vars = get_object_vars( $table );
897 $table = array_pop( $vars );
898 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
899 $endArray[] = $table;
906 public function timestamp( $ts = 0 ) {
907 $ct = new ConvertibleTimestamp( $ts );
909 return $ct->getTimestamp( TS_POSTGRES );
913 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
914 * to https://www.php.net/manual/en/ref.pgsql.php
916 * Parsing a postgres array can be a tricky problem, he's my
917 * take on this, it handles multi-dimensional arrays plus
918 * escaping using a nasty regexp to determine the limits of each
921 * This should really be handled by PHP PostgreSQL module
924 * @param string $text Postgreql array returned in a text form like {a,b}
925 * @param string[] $output
926 * @param int|bool $limit
930 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
931 if ( $limit === false ) {
932 $limit = strlen( $text ) - 1;
935 if ( $text == '{}' ) {
939 if ( $text[$offset] != '{' ) {
940 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
941 $text, $match, 0, $offset );
942 $offset += strlen( $match[0] );
943 $output[] = ( $match[1][0] != '"'
945 : stripcslashes( substr( $match[1], 1, -1 ) ) );
946 if ( $match[3] == '},' ) {
950 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
952 } while ( $limit > $offset );
957 public function aggregateValue( $valuedata, $valuename = 'value' ) {
961 public function getSoftwareLink() {
962 return '[{{int:version-db-postgres-url}} PostgreSQL]';
966 * Return current schema (executes SELECT current_schema())
970 * @return string Default schema for the current session
972 public function getCurrentSchema() {
973 $res = $this->query( "SELECT current_schema()", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
974 $row = $this->fetchRow( $res );
980 * Return list of schemas which are accessible without schema name
981 * This is list does not contain magic keywords like "$user"
984 * @see getSearchPath()
985 * @see setSearchPath()
987 * @return array List of actual schemas for the current sesson
989 public function getSchemas() {
991 "SELECT current_schemas(false)",
993 self::QUERY_IGNORE_DBO_TRX
995 $row = $this->fetchRow( $res );
998 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1000 return $this->pg_array_parse( $row[0], $schemas );
1004 * Return search patch for schemas
1005 * This is different from getSchemas() since it contain magic keywords
1010 * @return array How to search for table names schemas for the current user
1012 public function getSearchPath() {
1013 $res = $this->query( "SHOW search_path", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1014 $row = $this->fetchRow( $res );
1016 /* PostgreSQL returns SHOW values as strings */
1018 return explode( ",", $row[0] );
1022 * Update search_path, values should already be sanitized
1023 * Values may contain magic keywords like "$user"
1026 * @param array $search_path List of schemas to be searched by default
1028 private function setSearchPath( $search_path ) {
1030 "SET search_path = " . implode( ", ", $search_path ),
1032 self::QUERY_IGNORE_DBO_TRX
1037 * Determine default schema for the current application
1038 * Adjust this session schema search path if desired schema exists
1039 * and is not alread there.
1041 * We need to have name of the core schema stored to be able
1042 * to query database metadata.
1044 * This will be also called by the installer after the schema is created
1048 * @param string $desiredSchema
1050 public function determineCoreSchema( $desiredSchema ) {
1051 if ( $this->trxLevel() ) {
1052 // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
1053 // See https://www.postgresql.org/docs/8.3/sql-set.html
1054 throw new DBUnexpectedError(
1056 __METHOD__ . ": a transaction is currently active"
1060 if ( $this->schemaExists( $desiredSchema ) ) {
1061 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1062 $this->coreSchema = $desiredSchema;
1063 $this->queryLogger->debug(
1064 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1067 * Prepend our schema (e.g. 'mediawiki') in front
1068 * of the search path
1071 $search_path = $this->getSearchPath();
1072 array_unshift( $search_path, $this->addIdentifierQuotes( $desiredSchema ) );
1073 $this->setSearchPath( $search_path );
1074 $this->coreSchema = $desiredSchema;
1075 $this->queryLogger->debug(
1076 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1079 $this->coreSchema = $this->getCurrentSchema();
1080 $this->queryLogger->debug(
1081 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1082 $this->coreSchema . "\"\n" );
1087 * Return schema name for core application tables
1090 * @return string Core schema name
1092 public function getCoreSchema() {
1093 return $this->coreSchema;
1097 * Return schema names for temporary tables and core application tables
1100 * @return string[] schema names
1102 public function getCoreSchemas() {
1103 if ( $this->tempSchema ) {
1104 return [ $this->tempSchema, $this->getCoreSchema() ];
1107 $res = $this->query(
1108 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1110 $row = $this->fetchObject( $res );
1112 $this->tempSchema = $row->nspname;
1113 return [ $this->tempSchema, $this->getCoreSchema() ];
1116 return [ $this->getCoreSchema() ];
1119 public function getServerVersion() {
1120 if ( !isset( $this->numericVersion ) ) {
1121 $conn = $this->getBindingHandle();
1122 $versionInfo = pg_version( $conn );
1123 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1124 // Old client, abort install
1125 $this->numericVersion = '7.3 or earlier';
1126 } elseif ( isset( $versionInfo['server'] ) ) {
1128 $this->numericVersion = $versionInfo['server'];
1130 // T18937: broken pgsql extension from PHP<5.3
1131 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1135 return $this->numericVersion;
1139 * Query whether a given relation exists (in the given schema, or the
1140 * default mw one if not given)
1141 * @param string $table
1142 * @param array|string $types
1143 * @param bool|string $schema
1146 private function relationExists( $table, $types, $schema = false ) {
1147 if ( !is_array( $types ) ) {
1148 $types = [ $types ];
1150 if ( $schema === false ) {
1151 $schemas = $this->getCoreSchemas();
1153 $schemas = [ $schema ];
1155 $table = $this->realTableName( $table, 'raw' );
1156 $etable = $this->addQuotes( $table );
1157 foreach ( $schemas as $schema ) {
1158 $eschema = $this->addQuotes( $schema );
1159 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1160 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1161 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1162 $res = $this->query( $sql );
1163 if ( $res && $res->numRows() ) {
1172 * For backward compatibility, this function checks both tables and views.
1173 * @param string $table
1174 * @param string $fname
1175 * @param bool|string $schema
1178 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1179 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1182 public function sequenceExists( $sequence, $schema = false ) {
1183 return $this->relationExists( $sequence, 'S', $schema );
1186 public function triggerExists( $table, $trigger ) {
1188 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1189 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1190 AND tgrelid=pg_class.oid
1191 AND nspname=%s AND relname=%s AND tgname=%s
1193 foreach ( $this->getCoreSchemas() as $schema ) {
1194 $res = $this->query(
1197 $this->addQuotes( $schema ),
1198 $this->addQuotes( $table ),
1199 $this->addQuotes( $trigger )
1202 if ( $res && $res->numRows() ) {
1210 public function ruleExists( $table, $rule ) {
1211 $exists = $this->selectField( 'pg_rules', 'rulename',
1213 'rulename' => $rule,
1214 'tablename' => $table,
1215 'schemaname' => $this->getCoreSchemas()
1219 return $exists === $rule;
1222 public function constraintExists( $table, $constraint ) {
1223 foreach ( $this->getCoreSchemas() as $schema ) {
1224 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1225 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1226 $this->addQuotes( $schema ),
1227 $this->addQuotes( $table ),
1228 $this->addQuotes( $constraint )
1230 $res = $this->query( $sql );
1231 if ( $res && $res->numRows() ) {
1239 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1240 * @param string $schema
1243 public function schemaExists( $schema ) {
1244 if ( !strlen( $schema ) ) {
1245 return false; // short-circuit
1248 $res = $this->query(
1249 "SELECT 1 FROM pg_catalog.pg_namespace " .
1250 "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
1252 self::QUERY_IGNORE_DBO_TRX
1255 return ( $this->numRows( $res ) > 0 );
1259 * Returns true if a given role (i.e. user) exists, false otherwise.
1260 * @param string $roleName
1263 public function roleExists( $roleName ) {
1264 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1265 [ 'rolname' => $roleName ], __METHOD__ );
1267 return (bool)$exists;
1271 * @param string $table
1272 * @param string $field
1273 * @return PostgresField|null
1275 public function fieldInfo( $table, $field ) {
1276 return PostgresField::fromText( $this, $table, $field );
1280 * pg_field_type() wrapper
1281 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1282 * @param int $index Field number, starting from 0
1285 public function fieldType( $res, $index ) {
1286 return pg_field_type( ResultWrapper::unwrap( $res ), $index );
1289 public function encodeBlob( $b ) {
1290 return new PostgresBlob( pg_escape_bytea( $b ) );
1293 public function decodeBlob( $b ) {
1294 if ( $b instanceof PostgresBlob ) {
1296 } elseif ( $b instanceof Blob ) {
1300 return pg_unescape_bytea( $b );
1303 public function strencode( $s ) {
1304 // Should not be called by us
1305 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1308 public function addQuotes( $s ) {
1309 $conn = $this->getBindingHandle();
1311 if ( is_null( $s ) ) {
1313 } elseif ( is_bool( $s ) ) {
1314 return intval( $s );
1315 } elseif ( $s instanceof Blob ) {
1316 if ( $s instanceof PostgresBlob ) {
1319 $s = pg_escape_bytea( $conn, $s->fetch() );
1322 } elseif ( $s instanceof NextSequenceValue ) {
1326 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1329 public function makeSelectOptions( $options ) {
1330 $preLimitTail = $postLimitTail = '';
1331 $startOpts = $useIndex = $ignoreIndex = '';
1334 foreach ( $options as $key => $option ) {
1335 if ( is_numeric( $key ) ) {
1336 $noKeyOptions[$option] = true;
1340 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1342 $preLimitTail .= $this->makeOrderBy( $options );
1344 if ( isset( $options['FOR UPDATE'] ) ) {
1345 $postLimitTail .= ' FOR UPDATE OF ' .
1346 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1347 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1348 $postLimitTail .= ' FOR UPDATE';
1351 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1352 $startOpts .= 'DISTINCT';
1355 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1358 public function buildConcat( $stringList ) {
1359 return implode( ' || ', $stringList );
1362 public function buildGroupConcatField(
1363 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1365 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1367 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1370 public function buildStringCast( $field ) {
1371 return $field . '::text';
1374 public function streamStatementEnd( &$sql, &$newLine ) {
1375 # Allow dollar quoting for function declarations
1376 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1377 if ( $this->delimiter ) {
1378 $this->delimiter = false;
1380 $this->delimiter = ';';
1384 return parent::streamStatementEnd( $sql, $newLine );
1387 public function doLockTables( array $read, array $write, $method ) {
1389 foreach ( $write as $table ) {
1390 $tablesWrite[] = $this->tableName( $table );
1393 foreach ( $read as $table ) {
1394 $tablesRead[] = $this->tableName( $table );
1397 // Acquire locks for the duration of the current transaction...
1398 if ( $tablesWrite ) {
1400 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1404 if ( $tablesRead ) {
1406 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1414 public function lockIsFree( $lockName, $method ) {
1415 if ( !parent::lockIsFree( $lockName, $method ) ) {
1416 return false; // already held
1418 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1419 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1420 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1421 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1422 $row = $this->fetchObject( $result );
1424 return ( $row->lockstatus === 't' );
1427 public function lock( $lockName, $method, $timeout = 5 ) {
1428 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1429 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1430 $loop = new WaitConditionLoop(
1431 function () use ( $lockName, $key, $timeout, $method ) {
1432 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1433 $row = $this->fetchObject( $res );
1434 if ( $row->lockstatus === 't' ) {
1435 parent::lock( $lockName, $method, $timeout ); // record
1439 return WaitConditionLoop::CONDITION_CONTINUE;
1444 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1447 public function unlock( $lockName, $method ) {
1448 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1449 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1450 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1451 $row = $this->fetchObject( $result );
1453 if ( $row->lockstatus === 't' ) {
1454 parent::unlock( $lockName, $method ); // record
1458 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1463 public function serverIsReadOnly() {
1464 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1465 $row = $this->fetchObject( $res );
1467 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1470 public static function getAttributes() {
1471 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1475 * @param string $lockName
1476 * @return string Integer
1478 private function bigintFromLockName( $lockName ) {
1479 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1484 * @deprecated since 1.29
1486 class_alias( DatabasePostgres::class, 'DatabasePostgres' );